package com.smart.community.region.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.feign.region.dto.AddressInfoDTO;
import com.smart.community.region.dto.ResidentHouseholdAddDTO;
import com.smart.community.region.dto.ResidentHouseholdUpdateDTO;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Community;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.Resident;
import com.smart.community.region.entity.ResidentHousehold;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.ResidentHouseholdMapper;
import com.smart.community.region.mapper.ResidentMapper;
import com.smart.community.region.service.IAddressService;
import com.smart.community.region.service.IBuildingService;
import com.smart.community.region.service.ICommunityService;
import com.smart.community.region.service.IHouseholdService;
import com.smart.community.region.service.IResidentHouseholdService;
import com.smart.community.region.service.IUnitService;
import com.smart.community.region.service.IOwnerHouseholdService;
import com.smart.community.region.vo.PageResult;
import com.smart.community.region.vo.ResidentHouseholdVO;
import com.smart.community.region.vo.ResidentMobileHouseholdVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 住户房户关联服务实现类
 * 
 * @author Wu.Liang
 * @since 2025-07-28
 */
@Slf4j
@Service
public class ResidentHouseholdServiceImpl extends ServiceImpl<ResidentHouseholdMapper, ResidentHousehold>
		implements IResidentHouseholdService {
	@Autowired
	private DataScopeFeign dataScopeFeign;
	@Autowired
	private ResidentMapper residentMapper;
	@Autowired
	private IBuildingService buildingService;
	@Autowired
	private IUnitService unitService;
	@Autowired
	private IHouseholdService householdService;
	@Autowired
	private ICommunityService communityService;
	@Autowired
	private IAddressService addressService;
	@Autowired
	private IOwnerHouseholdService ownerHouseholdService;

	@Override
	public PageResult<ResidentHouseholdVO> getResidentList(Long householdId, Integer current, Integer size)
			throws Exception {
		log.info("查询房户住户列表，房户ID：{}，当前页：{}，每页条数：{}", householdId, current, size);

		// 使用自定义Mapper方法查询
		List<ResidentHouseholdVO> voList = baseMapper.selectResidentListWithInfo(householdId);
		// 补充社区/楼栋/单元/房号等信息
		for (ResidentHouseholdVO vo : voList) {
			enrichAddressFields(vo);
		}

		// 手动分页
		int start = (current - 1) * size;
		int end = Math.min(start + size, voList.size());
		List<ResidentHouseholdVO> pageList = voList.subList(start, end);

		return new PageResult<>(pageList, (long) voList.size(), current, size);
	}

	@Override
	public IPage<ResidentHouseholdVO> getResidentListWithConditions(Map<String, Object> queryParams, Integer current,
			Integer size) throws Exception {
		log.info("根据条件查询住户列表，查询条件：{}，当前页：{}，每页条数：{}", queryParams, current, size);

		// 创建分页对象
		Page<ResidentHousehold> page = new Page<>(current, size);

		// 构建查询条件
		LambdaQueryWrapper<ResidentHousehold> queryWrapper = new LambdaQueryWrapper<>();

		// 应用数据权限过滤
		applyDataPermissionFilter(queryWrapper);

		// 应用查询条件
		applyQueryConditions(queryWrapper, queryParams);

		// 执行分页查询
		Page<ResidentHousehold> resultPage = this.page(page, queryWrapper);

		// 转换为VO对象
		List<ResidentHouseholdVO> voList = resultPage.getRecords().stream().map(this::convertToVO)
				.collect(Collectors.toList());

		// 创建返回结果
		Page<ResidentHouseholdVO> result = new Page<>();
		result.setCurrent(resultPage.getCurrent());
		result.setSize(resultPage.getSize());
		result.setTotal(resultPage.getTotal());
		result.setPages(resultPage.getPages());
		result.setRecords(voList);

		log.info("查询住户列表完成，总记录数：{}，当前页记录数：{}", resultPage.getTotal(), voList.size());
		return result;
	}

	@Override
	public Long addResidentToHousehold(Long householdId, ResidentHouseholdAddDTO addDTO) throws Exception {
		log.info("新增住户到房户，房户ID：{}，住户ID：{}", householdId, addDTO.getResidentId());

		// 检查住户是否已在房户中
		Integer count = baseMapper.checkResidentInHousehold(addDTO.getResidentId(), householdId);
		if (count > 0) {
			throw new Exception("该住户已在此房户中");
		}

		// 新增逻辑实现
		ResidentHousehold entity = new ResidentHousehold();
		entity.setResidentId(addDTO.getResidentId());
		entity.setHouseholdId(householdId);
		entity.setResidentType(addDTO.getResidentType());
		entity.setMoveInDate(addDTO.getMoveInDate());
		entity.setMoveOutDate(addDTO.getMoveOutDate());
		entity.setContractStartDate(addDTO.getContractStartDate());
		entity.setContractEndDate(addDTO.getContractEndDate());
		entity.setMonthlyRent(addDTO.getMonthlyRent());
		entity.setDeposit(addDTO.getDeposit());
		entity.setContractNo(addDTO.getContractNo());
		entity.setRemark(addDTO.getRemark());
		entity.setStatus(SystemStatusEnum.ENABLED.getCode());

		this.save(entity);
		log.info("新增住户到房户成功，关联ID：{}", entity.getId());
		return entity.getId();
	}

	@Override
	public void removeResidentFromHousehold(Long householdId, Long residentId) throws Exception {
		log.info("移除住户从房户，房户ID：{}，住户ID：{}", householdId, residentId);

		// 查询关联信息
		ResidentHousehold entity = baseMapper.selectByHouseholdAndResident(householdId, residentId);
		if (entity == null) {
			throw new Exception("关联信息不存在");
		}

		// 逻辑删除
		entity.setDeleted(SystemStatusEnum.DELETED.getCode());
		
		// 乐观锁处理：确保版本号正确设置
		if (entity.getVersion() == null) {
			entity.setVersion(1);
		}
		
		this.updateById(entity);
		log.info("移除住户从房户成功");
	}

	@Override
	public void updateResidentHousehold(Long id, ResidentHouseholdUpdateDTO updateDTO) throws Exception {
		log.info("更新住户房户关联信息，关联ID：{}", id);

		// 更新逻辑实现
		ResidentHousehold entity = this.getById(id);
		if (entity == null) {
			throw new Exception("关联信息不存在");
		}

		entity.setResidentType(updateDTO.getResidentType());
		entity.setMoveInDate(updateDTO.getMoveInDate());
		entity.setMoveOutDate(updateDTO.getMoveOutDate());
		entity.setContractStartDate(updateDTO.getContractStartDate());
		entity.setContractEndDate(updateDTO.getContractEndDate());
		entity.setMonthlyRent(updateDTO.getMonthlyRent());
		entity.setDeposit(updateDTO.getDeposit());
		entity.setContractNo(updateDTO.getContractNo());
		entity.setRemark(updateDTO.getRemark());

		// 乐观锁处理：确保版本号正确设置
		if (entity.getVersion() == null) {
			entity.setVersion(1);
		}

		this.updateById(entity);
		log.info("更新住户房户关联信息成功");
	}

	@Override
	public PageResult<ResidentHouseholdVO> getHouseholdList(Long residentId, Integer current, Integer size)
			throws Exception {
		log.info("查询住户的房户列表，住户ID：{}，当前页：{}，每页条数：{}", residentId, current, size);

		// 使用自定义Mapper方法查询
		List<ResidentHouseholdVO> voList = baseMapper.selectHouseholdListWithInfo(residentId);
		// 补充社区/楼栋/单元/房号等信息
		for (ResidentHouseholdVO vo : voList) {
			enrichAddressFields(vo);
		}

		// 手动分页
		int start = (current - 1) * size;
		int end = Math.min(start + size, voList.size());
		List<ResidentHouseholdVO> pageList = voList.subList(start, end);

		return new PageResult<>(pageList, (long) voList.size(), current, size);
	}

	@Override
	public java.util.List<ResidentMobileHouseholdVO> listMobileHouseholdsByUserId(Long userId) throws Exception {
		log.info("移动端聚合查询当前用户房户列表，userId:{}", userId);
        java.util.List<ResidentMobileHouseholdVO> resultList = new ArrayList<>();

		// 1. 根据用户ID获取住户列表
		List<Resident> residents = residentMapper.selectByUserId(userId);
		if (residents == null || residents.isEmpty()) {
			return resultList;
		}

		// 2. 遍历住户，查询其房户列表并填充地址展示字段
		for (Resident resident : residents) {
			PageResult<ResidentHouseholdVO> householdResult = this.getHouseholdList(resident.getId(), 1,
					Integer.MAX_VALUE);
			if (householdResult == null || householdResult.getRecords() == null) {
				continue;
			}
			for (ResidentHouseholdVO householdVO : householdResult.getRecords()) {
				ResidentMobileHouseholdVO vo = new ResidentMobileHouseholdVO();
				vo.setHouseholdId(householdVO.getHouseholdId());
				vo.setRoomNumber(householdVO.getRoomNumber());
				vo.setResidentId(resident.getId());
				vo.setResidentName(resident.getRealName());
				vo.setResidentType(householdVO.getResidentType());
				vo.setResidentTypeName(householdVO.getResidentTypeName());

				try {
					AddressInfoDTO addressInfo = addressService.getAddressByHouseholdId(householdVO.getHouseholdId());
					if (addressInfo != null) {
						vo.setFullAddress(addressInfo.getFullAddress());
						vo.setCommunityId(addressInfo.getCommunityId()); // 新增：设置社区ID
						vo.setCommunityName(addressInfo.getCommunityName());
						vo.setBuildingName(addressInfo.getBuildingName());
						vo.setUnitName(addressInfo.getUnitName());
						vo.setRoomNumber(addressInfo.getRoomNumber());
						String displayName = String.format("%s%s%s%s",
								addressInfo.getCommunityName() != null ? addressInfo.getCommunityName() : "",
								addressInfo.getBuildingName() != null ? addressInfo.getBuildingName() : "",
								addressInfo.getUnitName() != null ? addressInfo.getUnitName() : "",
								addressInfo.getRoomNumber() != null ? addressInfo.getRoomNumber() : "");
						vo.setDisplayName(displayName);
					} else {
						vo.setFullAddress(householdVO.getRoomNumber());
						vo.setDisplayName(householdVO.getRoomNumber());
					}
				} catch (Exception e) {
					log.warn("获取房户地址信息失败，householdId:{}", householdVO.getHouseholdId(), e);
					vo.setFullAddress(householdVO.getRoomNumber());
					vo.setDisplayName(householdVO.getRoomNumber());
				}
				resultList.add(vo);
			}
		}

		// 3. 根据用户ID获取业主关联的房户ID列表
		List<Long> ownerHouseholdIds = new ArrayList<>();
		try {
			// 直接调用Service方法，而不是通过Feign接口
			List<com.smart.community.region.entity.OwnerHousehold> ownerHouseholds = ownerHouseholdService.getByOwnerId(userId);
			ownerHouseholdIds = ownerHouseholds.stream()
					.map(com.smart.community.region.entity.OwnerHousehold::getHouseholdId)
					.distinct()
					.collect(Collectors.toList());
			log.info("获取业主关联房户ID列表成功，userId:{}，房户ID数量:{}", userId, ownerHouseholdIds != null ? ownerHouseholdIds.size() : 0);
		} catch (Exception e) {
			log.warn("获取业主关联房户ID列表失败，userId:{}", userId, e);
		}

		// 4. 处理业主关联的房户
		if (ownerHouseholdIds != null && !ownerHouseholdIds.isEmpty()) {
			for (Long householdId : ownerHouseholdIds) {
				// 检查是否已经存在（避免重复）
				boolean exists = resultList.stream()
					.anyMatch(vo -> vo.getHouseholdId().equals(householdId));
				
				if (!exists) {
					ResidentMobileHouseholdVO vo = new ResidentMobileHouseholdVO();
					vo.setHouseholdId(householdId);
					vo.setResidentId(userId); // 业主ID就是用户ID
					vo.setResidentName("业主"); // 业主身份
					vo.setResidentType(1); // 业主类型
					vo.setResidentTypeName("业主");

					try {
						AddressInfoDTO addressInfo = addressService.getAddressByHouseholdId(householdId);
						if (addressInfo != null) {
							vo.setFullAddress(addressInfo.getFullAddress());
							vo.setCommunityId(addressInfo.getCommunityId());
							vo.setCommunityName(addressInfo.getCommunityName());
							vo.setBuildingName(addressInfo.getBuildingName());
							vo.setUnitName(addressInfo.getUnitName());
							vo.setRoomNumber(addressInfo.getRoomNumber());
							String displayName = String.format("%s%s%s%s",
									addressInfo.getCommunityName() != null ? addressInfo.getCommunityName() : "",
									addressInfo.getBuildingName() != null ? addressInfo.getBuildingName() : "",
									addressInfo.getUnitName() != null ? addressInfo.getUnitName() : "",
									addressInfo.getRoomNumber() != null ? addressInfo.getRoomNumber() : "");
							vo.setDisplayName(displayName);
						} else {
							vo.setFullAddress("未知地址");
							vo.setDisplayName("未知地址");
						}
					} catch (Exception e) {
						log.warn("获取业主房户地址信息失败，householdId:{}", householdId, e);
						vo.setFullAddress("未知地址");
						vo.setDisplayName("未知地址");
					}
					resultList.add(vo);
				}
			}
		}

		// 5. 去重并返回结果
		return resultList.stream()
			.collect(Collectors.toMap(
				ResidentMobileHouseholdVO::getHouseholdId,
				vo -> vo,
				(existing, replacement) -> existing // 如果有重复，保留第一个
			))
			.values()
			.stream()
			.collect(Collectors.toList());
	}

	/**
	 * 补全VO中的地址与层级名称字段
	 */
	private void enrichAddressFields(ResidentHouseholdVO vo) {
		if (vo == null || vo.getHouseholdId() == null) {
			return;
		}
		try {
			Household household = householdService.getById(vo.getHouseholdId());
			if (household != null) {
				vo.setRoomNumber(household.getRoomNumber());

				// 单元
				if (household.getUnitId() != null) {
					try {
						Unit unit = unitService.getById(household.getUnitId());
						if (unit != null) {
							vo.setUnitId(unit.getId());
							vo.setUnitName(unit.getUnitName());

							// 楼栋
							if (unit.getBuildingId() != null) {
								try {
									Building building = buildingService.getById(unit.getBuildingId());
									if (building != null) {
										vo.setBuildingId(building.getId());
										vo.setBuildingName(building.getBuildingName());

										// 社区
										if (building.getCommunityId() != null) {
											try {
												Community community = communityService
														.getById(building.getCommunityId());
												if (community != null) {
													vo.setCommunityId(community.getId());
													vo.setCommunityName(community.getCommunityName());
												}
											} catch (Exception ignored) {
											}
										}
									}
								} catch (Exception ignored) {
								}
							}
						}
					} catch (Exception ignored) {
					}
				}
			}
		} catch (Exception e) {
			log.warn("补全地址字段失败，房户ID：{}", vo.getHouseholdId(), e);
		}
	}

	/**
	 * 将实体转换为VO
	 */
	private ResidentHouseholdVO convertToVO(ResidentHousehold entity) {
		if (entity == null) {
			return null;
		}

		ResidentHouseholdVO vo = new ResidentHouseholdVO();
		vo.setId(entity.getId());
		vo.setResidentId(entity.getResidentId());
		vo.setHouseholdId(entity.getHouseholdId());
		vo.setResidentType(entity.getResidentType());
		vo.setMoveInDate(entity.getMoveInDate());
		vo.setMoveOutDate(entity.getMoveOutDate());
		vo.setContractStartDate(entity.getContractStartDate());
		vo.setContractEndDate(entity.getContractEndDate());
		vo.setMonthlyRent(entity.getMonthlyRent());
		vo.setDeposit(entity.getDeposit());
		vo.setContractNo(entity.getContractNo());
		vo.setApplyStatus(entity.getApplyStatus());
		vo.setStatus(entity.getStatus());
		vo.setRemark(entity.getRemark());
		vo.setCreateTime(entity.getCreateTime());
		vo.setUpdateTime(entity.getUpdateTime());

		// 设置住户身份名称
		vo.setResidentTypeName(getResidentTypeName(entity.getResidentType()));

		// 设置申请状态名称
		vo.setApplyStatusName(getApplyStatusName(entity.getApplyStatus()));

		// 设置状态名称
		vo.setStatusName(getStatusName(entity.getStatus()));

		// 获取住户详细信息
		try {
			Resident resident = residentMapper.selectById(entity.getResidentId());
			if (resident != null) {
				vo.setRealName(resident.getRealName());
				vo.setPhone(resident.getPhone());
				vo.setIdentityNo(resident.getIdentityNo());
				vo.setGender(resident.getGender());
				vo.setBirthday(resident.getBirthday());
			}
		} catch (Exception e) {
			log.warn("获取住户详细信息失败，住户ID：{}", entity.getResidentId(), e);
		}

		// 获取房户详细信息（包含社区、楼栋、单元信息）
		try {
			Household household = householdService.getById(entity.getHouseholdId());
			if (household != null) {
				vo.setRoomNumber(household.getRoomNumber());

				// 获取单元信息
				Unit unit = unitService.getById(household.getUnitId());
				if (unit != null) {
					vo.setUnitId(unit.getId());
					vo.setUnitName(unit.getUnitName());

					// 获取楼栋信息
					Building building = buildingService.getById(unit.getBuildingId());
					if (building != null) {
						vo.setBuildingId(building.getId());
						vo.setBuildingName(building.getBuildingName());

						// 获取社区信息
						Community community = communityService.getById(building.getCommunityId());
						if (community != null) {
							vo.setCommunityId(community.getId());
							vo.setCommunityName(community.getCommunityName());
						}
					}
				}
			}
		} catch (Exception e) {
			log.warn("获取房户详细信息失败，房户ID：{}", entity.getHouseholdId(), e);
		}

		return vo;
	}

	/**
	 * 获取住户身份名称
	 * 
	 * @param residentType 住户身份类型
	 * @return 身份名称
	 */
	private String getResidentTypeName(Integer residentType) {
		if (residentType == null) {
			return "未知";
		}
		switch (residentType) {
		case 1:
			return "户主";
		case 2:
			return "家庭成员";
		case 3:
			return "租客";
		case 4:
			return "临时居住";
		default:
			return "未知";
		}
	}

	/**
	 * 获取申请状态名称
	 * 
	 * @param applyStatus 申请状态
	 * @return 状态名称
	 */
	private String getApplyStatusName(Integer applyStatus) {
		if (applyStatus == null) {
			return "未知";
		}
		switch (applyStatus) {
		case 0:
			return "待审核";
		case 1:
			return "已通过";
		case 2:
			return "已拒绝";
		case 3:
			return "已撤销";
		default:
			return "未知";
		}
	}

	/**
	 * 获取状态名称
	 * 
	 * @param status 状态
	 * @return 状态名称
	 */
	private String getStatusName(Integer status) {
		if (status == null) {
			return "未知";
		}
		switch (status) {
		case 0:
			return "无效";
		case 1:
			return "有效";
		default:
			return "未知";
		}
	}

	/**
	 * 应用数据权限过滤 根据《智慧社区微服务架构总览.md》权威标准实现 1. 如果是超级管理员，可以查看所有数据 2.
	 * 如果不是超级管理员，但有关联物业公司，那么就取关联的物业公司，再取物业公司的社区集合，再取社区集合范围内的楼栋集合，再取楼栋集合范围内的单元集合，再取单元集合范围内的房户集合，分页展示
	 */
	private void applyDataPermissionFilter(LambdaQueryWrapper<ResidentHousehold> queryWrapper) {
		try {
			// 获取当前用户信息
			DataScopeInfo uds = dataScopeFeign.getUserDataScope(SecurityUtils.getCurrentUserId());

			// 超级管理员跳过数据权限过滤
			if (uds.isSuperAdmin()) {
				return;
			}

			// 非物业公司用户返回空结果
			if (!uds.isPropertyCompanyUser()) {
				queryWrapper.eq(ResidentHousehold::getId, -1L);
				return;
			}

			// 获取用户可访问的社区ID集合
			List<Long> communityIds = uds.getCommunityIds();
			if (communityIds.isEmpty()) {
				queryWrapper.eq(ResidentHousehold::getId, -1L); // 返回空结果
				return;
			}

			// 获取用户可访问的楼栋ID集合
			List<Long> buildingIds = getBuildingIdsByCommunityIds(communityIds);
			if (buildingIds.isEmpty()) {
				queryWrapper.eq(ResidentHousehold::getId, -1L); // 返回空结果
				return;
			}

			// 获取用户可访问的单元ID集合
			List<Long> unitIds = getUnitIdsByBuildingIds(buildingIds);
			if (unitIds.isEmpty()) {
				queryWrapper.eq(ResidentHousehold::getId, -1L); // 返回空结果
				return;
			}

			// 获取用户可访问的房户ID集合
			List<Long> householdIds = getHouseholdIdsByUnitIds(unitIds);
			if (householdIds.isEmpty()) {
				queryWrapper.eq(ResidentHousehold::getId, -1L); // 返回空结果
				return;
			}

			// 应用房户ID过滤条件
			queryWrapper.in(ResidentHousehold::getHouseholdId, householdIds);
		} catch (Exception e) {
			log.error("数据权限过滤失败", e);
			// 异常时返回空结果，确保系统稳定性
			queryWrapper.eq(ResidentHousehold::getId, -1L);
		}
	}

	/**
	 * 应用查询条件
	 */
	private void applyQueryConditions(LambdaQueryWrapper<ResidentHousehold> queryWrapper,
			Map<String, Object> queryParams) {
        // ===================== 基于层级的房户ID过滤（communityId / buildingId / unitId / householdId） =====================
        List<Long> filteredHouseholdIds = null;

        // 1) communityId → buildingIds → unitIds → householdIds
        if (queryParams.containsKey("communityId") && queryParams.get("communityId") != null) {
            Long communityId = (Long) queryParams.get("communityId");
            List<Long> buildingIds = getBuildingIdsByCommunityIds(Collections.singletonList(communityId));
            List<Long> unitIds = getUnitIdsByBuildingIds(buildingIds);
            List<Long> householdIds = getHouseholdIdsByUnitIds(unitIds);
            filteredHouseholdIds = new ArrayList<>(householdIds);
            log.debug("应用communityId过滤条件，communityId:{} → householdIds:{}", communityId, householdIds.size());
        }

        // 2) buildingId → unitIds → householdIds（与现有结果求交集）
        if (queryParams.containsKey("buildingId") && queryParams.get("buildingId") != null) {
            Long buildingId = (Long) queryParams.get("buildingId");
            List<Long> unitIds = getUnitIdsByBuildingIds(Collections.singletonList(buildingId));
            List<Long> householdIds = getHouseholdIdsByUnitIds(unitIds);
            
            if (filteredHouseholdIds != null) {
                // 求交集
                filteredHouseholdIds.retainAll(householdIds);
                log.debug("应用buildingId过滤条件，buildingId:{} → householdIds:{}，交集后:{}", buildingId, householdIds.size(), filteredHouseholdIds.size());
            } else {
                filteredHouseholdIds = new ArrayList<>(householdIds);
                log.debug("应用buildingId过滤条件，buildingId:{} → householdIds:{}", buildingId, householdIds.size());
            }
        }

        // 3) unitId → householdIds（与现有结果求交集）
        if (queryParams.containsKey("unitId") && queryParams.get("unitId") != null) {
            Long unitId = (Long) queryParams.get("unitId");
            List<Long> householdIds = getHouseholdIdsByUnitIds(Collections.singletonList(unitId));
            
            if (filteredHouseholdIds != null) {
                // 求交集
                filteredHouseholdIds.retainAll(householdIds);
                log.debug("应用unitId过滤条件，unitId:{} → householdIds:{}，交集后:{}", unitId, householdIds.size(), filteredHouseholdIds.size());
            } else {
                filteredHouseholdIds = new ArrayList<>(householdIds);
                log.debug("应用unitId过滤条件，unitId:{} → householdIds:{}", unitId, householdIds.size());
            }
        }

        // 4) householdId（与现有结果求交集）
        if (queryParams.containsKey("householdId") && queryParams.get("householdId") != null) {
            Long householdId = (Long) queryParams.get("householdId");
            
            if (filteredHouseholdIds != null) {
                // 求交集
                filteredHouseholdIds.retainAll(Collections.singletonList(householdId));
                log.debug("应用householdId过滤条件，householdId:{}，交集后:{}", householdId, filteredHouseholdIds.size());
            } else {
                filteredHouseholdIds = new ArrayList<>(Collections.singletonList(householdId));
                log.debug("应用householdId过滤条件，householdId:{}", householdId);
            }
        }

        // 应用层级过滤结果
        if (filteredHouseholdIds != null && !filteredHouseholdIds.isEmpty()) {
            queryWrapper.in(ResidentHousehold::getHouseholdId, filteredHouseholdIds);
        } else if (filteredHouseholdIds != null) {
            // 过滤结果为空，返回空结果
            queryWrapper.eq(ResidentHousehold::getId, -1L);
            return;
        }

        // ===================== 其他查询条件 =====================
        
        // 住户ID过滤
        if (queryParams.containsKey("residentId") && queryParams.get("residentId") != null) {
            Long residentId = (Long) queryParams.get("residentId");
            queryWrapper.eq(ResidentHousehold::getResidentId, residentId);
        }

        // 住户身份过滤
        if (queryParams.containsKey("residentType") && queryParams.get("residentType") != null) {
            Integer residentType = (Integer) queryParams.get("residentType");
            queryWrapper.eq(ResidentHousehold::getResidentType, residentType);
        }

        // 申请状态过滤
        if (queryParams.containsKey("applyStatus") && queryParams.get("applyStatus") != null) {
            Integer applyStatus = (Integer) queryParams.get("applyStatus");
            queryWrapper.eq(ResidentHousehold::getApplyStatus, applyStatus);
        }

        // 状态过滤
        if (queryParams.containsKey("status") && queryParams.get("status") != null) {
            Integer status = (Integer) queryParams.get("status");
            queryWrapper.eq(ResidentHousehold::getStatus, status);
        }

        // 姓名过滤（关联住户表）
        if (queryParams.containsKey("realName") && queryParams.get("realName") != null) {
            String realName = (String) queryParams.get("realName");
            try {
                List<Resident> residents = residentMapper.selectList(new LambdaQueryWrapper<Resident>()
                        .like(Resident::getRealName, realName));
                if (residents == null || residents.isEmpty()) {
                    // 无匹配住户，直接返回空
                    queryWrapper.eq(ResidentHousehold::getId, -1L);
                    return;
                }
                List<Long> residentIds = residents.stream().map(Resident::getId).collect(Collectors.toList());
                queryWrapper.in(ResidentHousehold::getResidentId, residentIds);
                log.debug("应用姓名模糊查询过滤条件: {}，匹配住户数：{}", realName, residentIds.size());
            } catch (Exception e) {
                log.warn("应用姓名过滤条件失败: {}", realName, e);
                // 保守处理：不添加姓名条件，避免影响其他条件
            }
        }

		// 基础过滤条件
		queryWrapper.eq(ResidentHousehold::getDeleted, SystemStatusEnum.NOT_DELETED.getCode());

		// 排序
		queryWrapper.orderByDesc(ResidentHousehold::getCreateTime);
	}

	/**
	 * 根据社区ID集合获取楼栋ID集合
	 */
    private List<Long> getBuildingIdsByCommunityIds(List<Long> communityIds) {
		try {
			log.debug("获取楼栋ID集合，社区ID集合: {}", communityIds);
            if (communityIds == null || communityIds.isEmpty()) {
                return new ArrayList<>();
            }
            List<Long> buildingIds = new ArrayList<>();

			for (Long communityId : communityIds) {
				try {
					// 调用楼栋服务获取该社区下的楼栋列表
					List<Building> buildings = buildingService.getBuildingsByCommunity(communityId);
					if (buildings != null) {
						buildingIds.addAll(buildings.stream().map(Building::getId).collect(Collectors.toList()));
					}
				} catch (Exception e) {
					log.warn("获取社区{}的楼栋列表失败", communityId, e);
				}
			}

			log.debug("获取楼栋ID集合完成，共{}个楼栋", buildingIds.size());
			return buildingIds;
		} catch (Exception e) {
			log.error("获取楼栋ID集合失败", e);
			return Collections.emptyList();
		}
	}

	/**
	 * 根据楼栋ID集合获取单元ID集合
	 */
    private List<Long> getUnitIdsByBuildingIds(List<Long> buildingIds) {
		try {
			log.debug("获取单元ID集合，楼栋ID集合: {}", buildingIds);
            if (buildingIds == null || buildingIds.isEmpty()) {
                return new ArrayList<>();
            }
            List<Long> unitIds = new ArrayList<>();

			for (Long buildingId : buildingIds) {
				try {
					// 调用单元服务获取该楼栋下的单元列表
					List<Unit> units = unitService.getUnitsByBuildingId(buildingId);
					if (units != null) {
						unitIds.addAll(units.stream().map(Unit::getId).collect(Collectors.toList()));
					}
				} catch (Exception e) {
					log.warn("获取楼栋{}的单元列表失败", buildingId, e);
				}
			}

			log.debug("获取单元ID集合完成，共{}个单元", unitIds.size());
			return unitIds;
		} catch (Exception e) {
			log.error("获取单元ID集合失败", e);
			return Collections.emptyList();
		}
	}

	/**
	 * 根据单元ID集合获取房户ID集合
	 */
    private List<Long> getHouseholdIdsByUnitIds(List<Long> unitIds) {
		try {
			log.debug("获取房户ID集合，单元ID集合: {}", unitIds);
            if (unitIds == null || unitIds.isEmpty()) {
                return new ArrayList<>();
            }
            List<Long> householdIds = new ArrayList<>();

			for (Long unitId : unitIds) {
				try {
					// 调用房户服务获取该单元下的房户ID列表
					List<Long> unitHouseholdIds = householdService.getHouseholdIdsByUnitId(unitId);
					if (unitHouseholdIds != null) {
						householdIds.addAll(unitHouseholdIds);
					}
				} catch (Exception e) {
					log.warn("获取单元{}的房户列表失败", unitId, e);
				}
			}

			log.debug("获取房户ID集合完成，共{}个房户", householdIds.size());
			return householdIds;
		} catch (Exception e) {
			log.error("获取房户ID集合失败", e);
			return Collections.emptyList();
		}
	}
}